//
//  FMDBManager.m
//  ProjectsOne
//
//  Created by iOS开发 on 2018/7/11.
//  Copyright © 2018年 iOS开发. All rights reserved.
//

#import "FMDBManager.h"
#import <FMDB.h>

@interface FMDBManager ()

@property (nonatomic, strong) FMDatabase *dataBase;

@end

@implementation FMDBManager

+ (instancetype)shareManage {
    static FMDBManager *manage = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manage = [[FMDBManager alloc] init];
    });
    return manage;
}

- (void)createSearchDataBase  {
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *filePath = [path stringByAppendingString:@"/searchHistory.sqlite"];
    _dataBase = [FMDatabase databaseWithPath:filePath];
    
    NSLog(@"%@", filePath);
    
    if ([_dataBase open]) {
        BOOL result = [_dataBase executeUpdate:[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS searchHistoryList (id integer PRIMARY KEY AUTOINCREMENT, keyword text);"]];
        if (result) {
            // 创建成功
        }
    }
}

- (void)insertionDataWithKeyword:(NSString *)keyword {
    // 插入
    if ([_dataBase open]) {
        
        [_dataBase executeUpdate:@"INSERT INTO searchHistoryList (keyword) VALUES (?)",keyword];
        [self deleteMessageLimit10];
    }
    [_dataBase close];
}

- (NSArray *)getAllData {
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
    if ([_dataBase open]) {
        //根据条件查询
        FMResultSet *resultSet = [_dataBase executeQuery:@"select * from searchHistoryList"];
        
        //遍历结果集合
        while ([resultSet next]) {
            NSString *keyword = [resultSet objectForColumn:@"keyword"];
            
            if (keyword.length != 0) {
                [arr addObject:keyword];
            }
        }
    }
    [_dataBase close];
    return [[arr reverseObjectEnumerator] allObjects];
}

- (BOOL)checkKeywordFromDB:(NSString *)keyword {
    BOOL result = NO;
    if ([_dataBase open]) {
        FMResultSet *resultSet = [_dataBase executeQuery:[NSString stringWithFormat:@"SELECT * FROM searchHistoryList WHERE keyword = '%@'", keyword]];
        //遍历结果集合
        while ([resultSet next]) {
            result = YES;
        }
    }
    [_dataBase close];
    return result;
}

- (void)deleteMessageLimit10 {
    [_dataBase executeUpdate:@"delete from searchHistoryList where (select count(id) from searchHistoryList)> 10 and id in (select id from searchHistoryList order by id ASC limit 1);"];
    
}

- (void)deleteDataWithKeyword:(NSString *)keyword {
    
    if ([_dataBase open]) {
        [_dataBase executeUpdate:@"delete from searchHistoryList where keyword = ?;" , keyword];
    }
    [_dataBase close];
}

- (void)deleteData {
    
    if ([_dataBase open]) {
        [_dataBase executeUpdate:@"delete from searchHistoryList"];
    }
    [_dataBase close];
}


@end
